package cn.wzut.edut.service;

import cn.wzut.edut.dao.inf.Information;
import cn.wzut.edut.dao.inf.User;
import cn.wzut.edut.dao.inf.Menu;
import cn.wzut.edut.dao.inf.Role;
import cn.wzut.edut.dao.pojo.table.SysMenu;
import cn.wzut.edut.dao.pojo.table.SysUser;
import cn.wzut.edut.jwt.JWTUtils;
import cn.wzut.edut.pojo.LoginInfo;
import cn.wzut.edut.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录服务层
 * by 叶庭辉
 */
@Service
public class LoginService {

    @Autowired
    User login;

    @Autowired
    Information information;

    @Autowired
    Role role;

    @Autowired
    Menu menu;

    /**
     * 登录功能
     * @param uid 用户名
     * @param pwd 密码
     * @return 验证成功返回用户信息，验证失败返回null
     */
    public LoginInfo Login(String uid, String pwd) {
        //核验hash后的pwd与数据库内数据是否一致
        SysUser userInfo = login.selectUser(uid);
        if (SysService.encrypt(pwd).equals(userInfo.getHashPassword()) && userInfo.getDelFlag().equals("1")) {
            // 身份验证成功，生成必要数据返回给前端
            // jwt payload部分构建
            Map<String, String> payload = new HashMap<>();
            payload.put("userid", userInfo.getId());
            // jwt token生成
            String token = JWTUtils.getToken(payload);
            // 用户信息 info
            Map<String, Object> info = new HashMap<>();
            info.put("userName", userInfo.getUserName());
            info.put("realName", userInfo.getRealName());
            info.put("roles", role.selectRoles(userInfo.getId()));
            // 动态路由数据 route
            List<SysMenu> route = menu.selectSysMenus(login.selectSysUserOnlyRole(userInfo.getId()));
            return new LoginInfo(token, info, route);
        }
        else{
            throw new ServiceException(-1, "登录失败");
        }
    }

}
